#include "chip.h"
#include "chipplace.h"
#include "woodensolitairescene.h"

Chip::Chip(WoodenSolitaireScene *scene, int row, int col, int size, const QColor &color) : scene(scene), row(row), col(col), size(size), color(color)
{
    prevPos = pos();
    setFlag(ItemIsMovable);
}

void Chip::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    painter->setBrush(QBrush(color));
    painter->drawEllipse(boundingRect());
}

QPainterPath Chip::shape() const
{
    QPainterPath path;
    path.addEllipse(boundingRect());
    return path;
}

QRectF Chip::boundingRect() const
{
    return QRectF(0, 0, size, size);
}

int Chip::getRow()
{
    return row;
}

int Chip::getCol()
{
    return col;
}

void Chip::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    prevPos = pos();
    QGraphicsItem::mousePressEvent(event);
}

void Chip::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    QList<QGraphicsItem*> placeList = collidingItems();
    if(placeList.size() == 1){
        ChipPlace *place = qgraphicsitem_cast<ChipPlace*>(placeList[0]);
        if(place != NULL && scene->jump(this, place)){
                setPos(place->pos());
                row = place->getRow();
                col = place->getCol();
                prevPos = pos();

                QGraphicsItem::mouseReleaseEvent(event);
                return;
        }
    }

    setPos(prevPos);
    QGraphicsItem::mouseReleaseEvent(event);
}




